#include <SDL2/SDL.h>
#include <SDL2/SDL2_gfxPrimitives.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define WIDTH  		640
#define HEIGHT 		480
#define OFFSET_X 	(WIDTH / 2)
#define OFFSET_Y 	(HEIGHT * 3 / 4)
#define PI 			3.1415926

void drawBellCurve(SDL_Renderer *renderer, float mu, float sigma);

int main(int argc, char **argv)
{
	float mu = 0, sigma = 1;

	if (argc == 3) {
		mu = (float) atoi(argv[1]);
		sigma = (float) atoi(argv[2]);
	}

	if (SDL_Init(SDL_INIT_VIDEO) < 0) {
		fprintf(stderr, "Initialize error: %s\n", SDL_GetError());
		exit(-1);
	}

	SDL_Window *window = SDL_CreateWindow("Bell Curve", 
			SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 
			WIDTH, HEIGHT, SDL_WINDOW_SHOWN);
	if (!window) {
		fprintf(stderr, "Create window error: %s\n", SDL_GetError());
		SDL_Quit();
		exit(-1);
	}

	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
	if (!renderer) {
		fprintf(stderr, "Create renderer error: %s\n", SDL_GetError());
		SDL_DestroyWindow(window);
		SDL_Quit();
		exit(-1);
	}
			
	// Set background
	SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
	SDL_RenderClear(renderer);

	// Set the color of curve
	SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
	drawBellCurve(renderer, mu, sigma);
	SDL_RenderPresent(renderer);

	int quit = 0;
	SDL_Event e;
	while (!quit) {
		while (SDL_PollEvent(&e)) {
			if (e.type == SDL_QUIT) 
				quit = 1;
		}
	}

	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

	exit(0);
}

void drawBellCurve(SDL_Renderer *renderer, float mu, float sigma)
{
	float x, y;
	float prev_x = -1, prev_y = -1;
	float scaling_factor = 1000;

	for (x = 0; x < WIDTH; x += 0.1f) {
		y = (1 / sqrt(2 * PI * sigma)) * exp(-0.5 * pow((x - mu - OFFSET_X) / sigma, 2));
		y *= scaling_factor;

		if (prev_x != -1 && prev_y != -1)
			aalineColor(renderer, (int) prev_x, (int) prev_y, 
					(int) x, (int) (OFFSET_Y - y), 0xFF0000FF);
		prev_x = x;
		prev_y = OFFSET_Y - y;
	}
}
